﻿using ConsoleApp.wayline;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        //static void Main(string[] args)
        //{
        //}
        static async Task Main(string[] args)
        {
            

            //var urls = new List<string>
            //{
            //    "http://39.100.42.60/swsc/tiles/blank_tile.png",
            //    "http://39.100.42.60/swsc/dfs/ImageDataset/202304051008000040102/%E5%9B%BE%E7%89%87%E7%BB%84006198/DJI_20230326122354_0079_T_R03-H04-1217_%E6%95%85%E9%9A%9C000001.JPG",
            //    "http://39.100.42.60/swsc/dfs/geojson/100801001/20230213山西大同熊猫光伏电站矢量数据.geojson"
            //};

            //var tasks = new List<Task>();

            //foreach (var url in urls)
            //{
            //    tasks.Add(DownloadFileAsync(url));
            //}

            //await Task.WhenAll(tasks);
            //Console.WriteLine("All files have been downloaded.");
            //Console.WriteLine("------------");
            string blockID = "huazhi-H01-1";
            blockID = "百科02-1";
            blockID = CommToolHelper.replaceChineseCharactersWithEmpty(blockID);
            string newBlockID = blockID.Contains("、") ? blockID.Split('、')[0] : blockID.Split(',')[0];
            string[] info = Regex.Replace(newBlockID, "[A-Za-z ]", "").Replace("_", "-").Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string s in info)
            {
                Console.WriteLine(s);
            }
            Console.WriteLine("===================================");
            // c6eead84c2d304c422ded905090b7e66b42b7be8cf5522ce1bb7de1526cab11d
            //Console.WriteLine(HttpHelper.GenerateFileSHA256Identifier("D:\\ides\\android-studio-ide-202.7351085-windows.zip"));
            // ee9aa08ebd4dde5fbb4f635d1d568593
            //Console.WriteLine(HttpHelper.GenerateFileMD5Identifier("D:\\ides\\android-studio-ide-202.7351085-windows.zip"));
            Dictionary<string, string> formParams = new Dictionary<string, string>();
            formParams.Add("fileMd5", "23c8dd007bbd98e85bbbe35fe955dc86");
            //string res = HttpHelper.postFormData("http://localhost:8083/solar-verse/api/v1/common/file/check?organNo=100702002", formParams);
            //HttpHelper.postFormForBigFile("C:\\Users\\cherr\\Videos\\Captures\\腾讯会议 2023-04-20 14-31-59.mp4");

            //Console.WriteLine(IsImageValid(@"D:\问题图片\DJI_20240327131523_0408_T_R01-H04-4051.JPG"));
            Console.WriteLine("--------");

            // 输入GeoJSON文件路径和输出DXF文件路径
            
            Geojson2CADHelper geojson2CADHelper = new Geojson2CADHelper();
            //geojson2CADHelper.Convert(@"D:\PowerStations\国家光伏储能实证实验平台大庆基地一期\VectorFile\01期03区NEW.geojson",
            //    @"D:\PowerStations\国家光伏储能实证实验平台大庆基地一期\VectorFile\01期03区NEW.dwg");

            var converter = new GeoJsonToCadConverter1();
            string inputGeoJson = "D:/downloads/baidu/25号区域/25result.geojson";
            string outputDxf = "D:/downloads/baidu/25号区域/25result-02.dxf";

            inputGeoJson = @"D:\PowerStations\国家光伏储能实证实验平台大庆基地一期\VectorFile\01期03区NEW.geojson";
            outputDxf = @"D:\PowerStations\国家光伏储能实证实验平台大庆基地一期\VectorFile\01期03区NEW.dxf";


            try
            {
                //converter.Convert(inputGeoJson, outputDxf);
                Console.WriteLine("转换成功完成!");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"转换过程中发生错误: {ex.Message}");
            }
            string tiffDir = @"D:\downloads\大唐海南屋顶光伏数据";
            string outputDir = @"D:\downloads\大唐海南屋顶光伏数据\result_tiles";
            //GeoTiffSplitter.SplitGeoTiffWithColorTable(Path.Combine(tiffDir, "result_T.tif"), Path.Combine(tiffDir, GeoTiffSplitter.GEO_TIFF_SPLIT_DIR_NAME), 512, true, true);

            // 处理两个重叠的GeoTIFF文件
            string[] files = {
                @"D:\downloads\大唐海南屋顶光伏数据\result_T.tif",  // 热红外图像
                @"D:\downloads\大唐海南屋顶光伏数据\result_V.tif"   // 可见光图像
            };
            var types = new List<string> { "T", "V" };
            //MultiGeoTiffSplitter.SplitMultipleGeoTiffs(
            //    new List<string> ( files ),
            //    types,
            //    outputDir,
            //    tileSize: 1024,
            //    overwrite: true
            //);

            // 红外可见光geotiff切图
            // UnifiedGeoTiffSplitter.SplitMultipleGeoTiffs(
            //    files,
            //    outputDir,
            //    tileSize: 512,
            //    overwrite: true
            //);

            //GeoTiffOverlapProcessor.ProcessOverlappedGeoTiffs(
            //    inputPaths: files,
            //    outputDir: "D:/downloads/大唐海南屋顶光伏数据/result_tiles",
            //    tileSize: 512
            //);
            // 示例数据 (无人机在纽约中央公园上方)
            double droneLon = 100.20005;   // 经度
            double droneLat = 36.003380555555559;    // 纬度
            double droneAlt = 68.662;      // 高度 (m)

            // 相机姿态 (指向正下方)
            double yaw = -89.3;     // 偏航角
            double pitch = -90.0;   // 俯仰角 (下视为负值)
            double roll = 180;      // 滚转角
            /*
            // 计算图像中心坐标
            var (lon, lat) = DroneCameraImageHelper.CalculateImageCenter(
                droneLon, droneLat, droneAlt, yaw, pitch, roll);

            Console.WriteLine("Image Center Coordinates:");
            Console.WriteLine($"Longitude: {lon}");
            Console.WriteLine($"Latitude: {lat}");

            // 基本高精度计算
            var (lon1, lat1) = HighPrecisionDroneConverter.CalculateImageCenter(
                droneLon, droneLat, droneAlt, yaw, pitch, roll);

            Console.WriteLine("\n基本高精度计算结果:");
            Console.WriteLine("经度: {0:F12}", lon1);
            Console.WriteLine("纬度: {0:F12}", lat1);

            // 迭代法提高精度
            var (lon2, lat2) = HighPrecisionDroneConverter.CalculateImageCenterIterative(
                droneLon, droneLat, droneAlt, yaw, pitch, roll);

            Console.WriteLine("\n迭代法高精度计算结果:");
            Console.WriteLine("经度: {0:F12}", lon2);
            Console.WriteLine("纬度: {0:F12}", lat2);

            droneTargetLocator();

            CoordinateConverter.LMain();
            Console.WriteLine();
            Doubao.DroneCoordinateCalculator.DroneCoordinateCalculator.LMain();
            DpGeospatialCalculator.LMain();
            PhotoGeotagCalculatorProgram.LMain();
            DroneGeoreference.LMain();
            DroneGeoreference.LMain1();
            */
            //Doubao.DoubaoDroneGeoConvert.LMain();
            //chatgpt.UAVGeoCalculator.LMain();
            //chatgpt.UAVGeoCalculator.LMain1();
            //chatgpt.UAVGeoCalculator.LMain();
            //chatgpt.UAVGeoCalculator.LMain1();
            //YoloOnnxRuntimeHelper.LMain();
            //YoloOnnxRuntimeDetector detector = new YoloOnnxRuntimeDetector("D:/data/var/flygo/AI/onnx/defect_recgon_X_roof.onnx", @"D:\data\var\flygo\AI\onnx\defect_recgon_X.yaml");
            //detector.Detect(@"D:\data\PowerStations\晶科蚌埠\WorkProjects\晶科蚌埠_光伏巡检_第1次作业\tiffsplits\tile_1_2_T.png");

            //Gdal2tilesHelper1.GenerateTiles(@"D:\红外武川_T.tif", @"D:\红外武川", 1, 22, 256, ResamplingMethod.Cubic, TileScheme.TMS, true);
            // Gdal2TilesWrapper.LMain();
            // TileCoordinateCalculator.test();
            // generateWayline();
            convertMbtiles();
        }
        static void convertMbtiles()
        {
            try
            {
                // 配置转换参数
                string tilesDirectory = @"E:\PowerStationsBJP\大同领跑者光伏电站\BasicMap\05-06-01-02";
                string outputMbtilesPath = @"E:\PowerStationsBJP\大同领跑者光伏电站\BasicMap\100801003.mbtiles";
                string tileFormat = "png";
                bool isTmsFormat = true;

                // 设置元数据
                var metadata = new Dictionary<string, string>
                {
                    {"name", "MyMap"},
                    {"description", "转换自本地瓦片的地图数据"},
                    {"attribution", "© 2023 My Company"},
                    {"bounds", "-180,-90,180,90"},
                    {"minzoom", "1"},
                    {"maxzoom", "22"}
                };

                Console.WriteLine("开始转换瓦片到MBTiles...");
                Console.WriteLine($"瓦片目录: {tilesDirectory}");
                Console.WriteLine($"输出文件: {outputMbtilesPath}");

                // 在非async方法中调用异步方法，使用Wait()等待完成
                MBTilesConvert.Convert(
                    tilesDirectory,
                    outputMbtilesPath,
                    tileFormat,
                    isTmsFormat,
                    metadata,
                    (current, total) =>
                    {
                        int percentage = (int)((double)current / total * 100);
                        Console.Write($"\r转换进度: {percentage}% ({current}/{total})");
                    }
                ).Wait(); // 关键：使用Wait()等待异步任务完成

                Console.WriteLine("\n转换完成！");
            }
            catch (AggregateException ex)
            {
                // 处理异步操作中抛出的异常（包装在AggregateException中）
                Console.WriteLine($"\n转换失败: {ex.InnerException?.Message ?? ex.Message}");
                if (ex.InnerException != null)
                    Console.WriteLine($"错误详情: {ex.InnerException.StackTrace}");
            }
            catch (Exception ex)
            {
                // 处理其他同步异常
                Console.WriteLine($"\n转换失败: {ex.Message}");
                Console.WriteLine($"错误详情: {ex.StackTrace}");
            }

            Console.WriteLine("\n按任意键退出...");
            Console.ReadKey();
        }
        static void generateWayline()
        {
            WaylineGenerateParams waylineParams = new WaylineGenerateParams();
            waylineParams.waylineName = "测试航线" + DateTime.Now.ToString("yyMMdd");
            waylineParams.waylineDestDir = @"D:\data\var\flygo\data\uavwayline\101701001";
            waylineParams.waylineTempDir = @"D:\data\var\flygo\data\uavwayline\101701001\temp";
            DjiWaylineHelper.generateKmz(waylineParams);
        }
        static void droneTargetLocator()
        {
            try
            {
                // 无人机参数（假设值）
                double droneLon = 100.20005;
                double droneLat = 36.003380555555559;
                double droneAlt = 100.0;  // 高度100米
                double yaw = 45.0;        // 正北为0°，顺时针45°
                double pitch = -60.0;     // 俯仰角-60°（向下）
                double roll = 2.0;         // 滚转角2°

                // 相机参数
                double focalLength = 12;   // 焦距24mm
                double pixelSize = 12;     // 像元尺寸12μm
                double width = 640;        // 图像宽度
                double height = 512;       // 图像高度

                // 目标区域 [(150, 100), (200, 140)]
                double x1 = 133, y1 = 220;
                double x2 = 158, y2 = 260;

                // 创建相机模型
                var camera = new DroneTargetLocator.CameraModel(focalLength, pixelSize, width, height);

                Console.WriteLine("相机参数:");
                Console.WriteLine($"焦距: {focalLength}mm");
                Console.WriteLine($"像元尺寸: {pixelSize}μm");
                Console.WriteLine($"图像尺寸: {width}x{height}像素");
                Console.WriteLine($"计算焦距: {camera.FocalLengthX:F1}像素");
                Console.WriteLine($"主点位置: ({camera.PrincipalPointX:F1}, {camera.PrincipalPointY:F1})");

                Console.WriteLine("\n无人机参数:");
                Console.WriteLine($"位置: ({droneLon:F9}, {droneLat:F9})");
                Console.WriteLine($"高度: {droneAlt:F2}米");
                Console.WriteLine($"姿态: 偏航={yaw}°, 俯仰={pitch}°, 滚转={roll}°");

                Console.WriteLine("\n目标区域:");
                Console.WriteLine($"左上角: ({x1}, {y1})");
                Console.WriteLine($"右下角: ({x2}, {y2})");
                Console.WriteLine($"中心点: ({(x1 + x2) / 2}, {(y1 + y2) / 2})");

                // 定位目标区域中心点
                var (centerLon, centerLat) = DroneTargetLocator.TargetLocator.LocateTargetArea(
                    droneLon, droneLat, droneAlt,
                    yaw, pitch, roll,
                    camera, x1, y1, x2, y2);

                Console.WriteLine("\n目标区域中心点坐标:");
                Console.WriteLine($"经度: {centerLon:F9}");
                Console.WriteLine($"纬度: {centerLat:F9}");

                // 定位目标区域四个角点
                var corners = DroneTargetLocator.TargetLocator.LocateTargetAreaCorners(
                    droneLon, droneLat, droneAlt,
                    yaw, pitch, roll,
                    camera, x1, y1, x2, y2);

                Console.WriteLine("\n目标区域角点坐标:");
                Console.WriteLine($"左上角: ({corners.TopLeft.Lon:F9}, {corners.TopLeft.Lat:F9})");
                Console.WriteLine($"右上角: ({corners.TopRight.Lon:F9}, {corners.TopRight.Lat:F9})");
                Console.WriteLine($"右下角: ({corners.BottomRight.Lon:F9}, {corners.BottomRight.Lat:F9})");
                Console.WriteLine($"左下角: ({corners.BottomLeft.Lon:F9}, {corners.BottomLeft.Lat:F9})");

                // 计算目标区域尺寸
                double widthMeters = DroneTargetLocator.GeodeticUtils.CalculateGeodeticDistance(
                    corners.TopLeft.Lat, corners.TopLeft.Lon,
                    corners.TopRight.Lat, corners.TopRight.Lon);

                double heightMeters = DroneTargetLocator.GeodeticUtils.CalculateGeodeticDistance(
                    corners.TopLeft.Lat, corners.TopLeft.Lon,
                    corners.BottomLeft.Lat, corners.BottomLeft.Lon);

                Console.WriteLine("\n目标区域尺寸:");
                Console.WriteLine($"宽度: {widthMeters:F2}米");
                Console.WriteLine($"高度: {heightMeters:F2}米");
                Console.WriteLine($"面积: {widthMeters * heightMeters:F2}平方米");

                // 计算目标中心与无人机位置的距离和方位
                double distance = DroneTargetLocator.GeodeticUtils.CalculateGeodeticDistance(
                    droneLat, droneLon, centerLat, centerLon);

                double azimuth = DroneTargetLocator.GeodeticUtils.CalculateAzimuth(
                    droneLat, droneLon, centerLat, centerLon);

                Console.WriteLine("\n目标相对于无人机的位置:");
                Console.WriteLine($"距离: {distance:F2}米");
                Console.WriteLine($"方位角: {azimuth:F1}° (正北为0°)");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"错误: {ex.Message}");
            }
        }

        public static bool IsImageValid(string imagePath)
        {
            try
            {
                using (System.Drawing.Image.FromFile(imagePath))
                {
                    // 图片加载成功，没有异常，认为是有效的图片
                    return true;
                }
            }
            catch
            {
                // 图片无法加载，可能损坏或格式不支持
                return false;
            }
        }

        static async Task DownloadFileAsync(string url)
        {
            using (var httpClient = new HttpClient())
            {
                using (var response = await httpClient.GetAsync(url))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var fileName = Path.GetFileName(url);
                        using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
                        {
                            await response.Content.CopyToAsync(fileStream);
                        }

                        Console.WriteLine($"File {fileName} has been downloaded.");
                    }
                    else
                    {
                        Console.WriteLine($"Failed to download file from {url}. Status code: {response.StatusCode}");
                    }
                }
            }
        }
    }
}
